function inits() {
    $("#jqGrid").Grid({
        url: '../devmaintenrepair/list',
        colModel: [
            {label: '产线', name: 'devProductName', index: 'DEV_PRODUCT_NAME'},
            {label: '工序号', name: 'devProceNo', index: 'DEV_PROCE_NO', width: 60},
            {label: '工序', name: 'devProceName', index: 'DEV_PROCE_NAME'},
            {label: '设备名称', name: 'devName', index: 'DEV_NAME', width: 120},
            {
                label: '来源', name: 'source', index: 'SOURCE', width: 60,
                formatter: function (value, col, row) {
                    return sysEnums.TICKET_SOURCE[value];
                }
            },
            {label: '维修开始时间', name: 'repairStartDate', index: 'REPAIR_START_DATE', width: 90},
            {label: '报警代码', name: 'faultCode', index: 'FAULT_CODE', width: 80},
            {label: '报警描述', name: 'faultDesc', index: 'FAULT_DESC', width: 80},
            {label: '故障时长(分)', name: 'faultNum', index: 'FAULT_NUM', width: 70},
            {label: '维修人', name: 'repairUsername', index: 'REPAIR_USER', width: 50},
            {
                label: '换件记录', width: 60, sortable: false,
                formatter: function (value, col, row) {
                    return "<button title='' class='btn btn-outline btn-info' onclick='vm.addReplacePartRecord(\"" + row.id + "\")'><i class='fa fa-file-text-o'></i></button>";
                }
            },
            {
                label: '维修详情', width: 60, sortable: false,
                formatter: function (value, col, row) {
                    return "<button title='' class='btn btn-outline btn-info' onclick='vm.viewRepairDetail(\"" + row.id + "\")'><i class='fa fa-file-text-o'></i></button>";
                }
            },
            {label: '设备类型', name: 'devKind', hidden: true}
        ]
    });
}

$(function () {
    var ids = getQueryString("id");
    if (ids != null) {
        vm.showList = false;
        vm.add();
        //根据id查询维修工单信息
        Ajax.request({
            url: "../devmaintenwork/info/" + ids,
            async: false,
            successCallback: function (r) {
                vm.devMaintenRepair.devId = r.devMaintenWork.devId
                vm.devMaintenRepair.devName = r.devMaintenWork.devName;
            }
        })
    } else {
        vm.showList = true;
        inits();
        // 加载列表页的设备故障类型树
        vm.getFaultTree();
        // 初始化表单页用到的设备故障类型树
        vm.getFaultTypeTree();

        //$("#jqGrid").setGridWidth($(window).width());
    }
});

//定义树
var faultTree;
//定义树
var setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "pid",
            rootPId: 0
        },
        key: {
            url: "nourl",
            name: "name" //name 与 typeName 绑定
        },
    },
    callback: {
        onClick: function () {
            let node = faultTree.getSelectedNodes();
            if (node[0].typePid != '0') {
                vm.q.faultCategoryId = node[0].id;
                vm.query()
            }
        }
    }
};

// 表单页用到的设备类型故障树
var formAlarmCategoryTree;
//定义设备报警/故障树配置
var alarmCategoryTreeSetting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "pid",
            rootPId: 0
        },
        key: {
            url: "nourl",
            name: "name" //name 与 typeName 绑定
        },
    }
};

var vm = new Vue({
    el: '#rrapp',
    data: {
        showList: true,
        title: null,
        typeName: "",
        devMaintenRepair: {
            devId: '',
            devCode: '',
            devName: '',
            maintenRecordId: '',
            faultCode: '',
            faultDesc: '',
            vfgId: '',
            cccId: '',
            faultId: '',
            faultCategoryId: '', // 报警分类名称
            faultCategoryName: '', // 报警分类名称
            recordDescr: '',
            reason: '',
            solution: '',
            remark: '',
            id: '',
            startDateTime: '', // Date-Picker组件用
            endDateTime: '', // Date-Picker组件用
            repairStartDate: '',
            repairEndDate: '',
            big: '',//报警分类大类
            middle: '',//报警分类中
            small: ''//报警分类小类
        },
        vrtList: [], // VRT 大类
        vfgList: [], // VFG 种类
        cccList: [], // CCC 小类
        alarmList: [], // 报警代码列表
        flag: '0', //是否新增报警代码新增
        deviceInfoList: {},

        ruleValidate: {
            devId: [
                {required: true, message: '设备编号不能为空', trigger: 'blur'}
            ],
            faultCode: [
                {required: true, type: 'string', message: '报警代码不能为空', trigger: 'change'},
                {
                    trigger: 'blur'
                }
            ],
            faultDesc: [
                {required: true, message: '报警描述不能为空', trigger: 'blur'},
            ],
            startDateTime: [
                {required: true, type: 'date', message: '请选择开始维修时间', trigger: 'change'},
            ],
            endDateTime: [
                {required: true, type: 'date', message: '请选择结束维修时间', trigger: 'change'}
            ],
            recordDescr: [
                {required: true, type: 'string', message: '请输入故障描述', trigger: 'blur'}
            ],
            reason: [
                {required: true, type: 'string', message: '请输入原因分析', trigger: 'blur'}
            ],
            solution: [
                {required: true, type: 'string', message: '请输入解决办法', trigger: 'blur'}
            ]
        },
        repairStartRange: [], // 维修开始查询时间区间
        q: {
            workshopId: '', // 车间ID
            devCode: '', // 设备编码
            name: '', // 设备名称
            spareName: '', // 备件名称
            spareSpec: '', // 备件规格
            faultCategoryId: '', // 报警/故障分类ID
            beginTime: '',
            endTime: ''
        },
        replaceSpareListCols: [
            {title: '备件编码', key: 'spareCode'},
            {title: '名称', key: 'name'},
            {title: '规格', key: 'spec'},
            {title: '更换数目', key: 'num'}
        ],
        replaceSpareList: [],
        workshopList: [] // 所属车间下拉option列表
    },
    created: function () {
        // 加载车间列表
        this.loadWorshopList();
    },
    methods: {
        // 加载报警代码
        loadAlarmCategory(queryCondition, callback) {
            Ajax.request({
                url: '../alarmcategory/queryAll?' + queryCondition,
                async: true,
                successCallback: data => {
                    if (data.list == 0) {
                        alert('无可选设备报警分类，请等待维护完毕后再进行完善！')
                        return;
                    }
                    callback(data.list);
                }
            });
        },
        /*
               * 1.切换时清空小类 和小类数组
               * 2. 获取小类数组
               * */
        handleVfgChange(vfgOption) {
            if (!vfgOption) {
                return;
            }
            // 清空
            vm.devMaintenRepair.faultCategoryId = '';
            vm.devMaintenRepair.faultCategoryName = '';
            vm.devMaintenRepair.faultId = '';
            vm.devMaintenRepair.faultCode = '';
            vm.devMaintenRepair.faultDesc = '';
            // 清空CCC列表
            this.cccList = [];
            // 清空设备报警代码列表
            this.alarmList = [];
            // 加载CCC列表
            vm.loadAlarmCategory('pid=' + vfgOption, function (dataList) {
                vm.cccList = dataList;
            });
        },
        /*
            报警小类切换时 1.会加载出来报警代码，自动回填
        */
        handleCccChange(cccOption) {
            // 清空设备报警代码库+设备报警西悉尼
            this.devMaintenRepair.faultId = '';
            this.devMaintenRepair.faultCode = '';
            this.devMaintenRepair.faultDesc = '';
            this.alarmList = [];
            // 设置CCCID
            this.devMaintenRepair.faultCategoryId = cccOption;
            this.loadDevAlarmList(cccOption, vm.devMaintenRepair.devId);
        },
        // 加载设备备件代码列表
        loadDevAlarmList(cccId, devId) {
            Ajax.request({
                url: '../alarmcodebase/queryAll?alarmCategoryId=' + cccId + '&devId=' + devId,
                async: true,
                successCallback: data => {
                    this.alarmList = data.list;
                }
            });
        },
        selectAlarmCategory: function () {
            openWindow({
                title: "选择报警/故障分类",
                area: ['400px', '600px'],
                content: jQuery("#faultTypeLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var selectedNodes = formAlarmCategoryTree.getSelectedNodes();
                    if (!selectedNodes || selectedNodes.length == 0) {
                        alert('请选择故障类型！');
                        return;
                    }
                    vm.devMaintenRepair.faultCategoryId = selectedNodes[0].id;
                    vm.devMaintenRepair.faultCategoryName = selectedNodes[0].name;
                    layer.close(index);
                }
            });
        },
        /*
        * 1.报警代码切换
        * */
        showLoc: function (type) {
            if (type == 0) {
                // 手动输入库位
                vm.flag = 1;
                this.$set(this.devMaintenRepair, 'faultCode', '')
            } else if (type == 1) {
                // 从现有库位中选择
                this.$set(this.devMaintenRepair, 'faultCode', '')
                vm.flag = 0;
            }
        },
        loadWorshopList: function () {
            var _this = this;
            Ajax.request({
                url: '../sys/dept/listByDeptLevel?deptLevel=2',
                async: true,
                successCallback: data => {
                    this.workshopList = data.list;
                }
            });
        },
        // 关联备件换件记录
        addReplacePartRecord: function (ticketId, devKind) {
            openWindow({
                type: 2,
                area:['100%','100%'],
                title: '<i class="fa fa-bars"></i> 维修换件记录',
                content: '../spare/sparepartconsumrecord.html?businessId=' + ticketId + '&type=REPAIR&materialType=2'
            })
        },
        getDeviceInfo: function () {
            openWindow({
                type: 2,
                title: '<i class="fa fa-file-text-o"></i> 选择设备',
                content: '../sys/deviceInfoSelect.html',
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var iframeWin = window["layui-layer-iframe" + index];
                    var res = iframeWin.getDeviceInfo();
                    if (!res) {
                        iview.Message.error("请选择一条记录");
                    } else {
                        vm.devMaintenRepair.devCode = res.devCode;
                        vm.devMaintenRepair.devName = res.devName;
                        vm.devMaintenRepair.devId = res.id;
                        // 加载报警VRT类
                        vm.loadAlarmCategory('pid=0&categoryCode=' + res.devTypeS, function (vrtList) {
                            vm.devMaintenRepair.vrtId = vrtList[0].id;
                            vm.devMaintenRepair.vrtName = vrtList[0].name;
                            // 继续加载VFG列表
                            vm.loadAlarmCategory('pid=' + vm.devMaintenRepair.vrtId, function (vfgList) {
                                vm.vfgList = vfgList;
                                vm.devMaintenRepair.vfgId = '';
                                vm.devMaintenRepair.faultCategoryId = '';
                                vm.devMaintenRepair.faultCategoryName = '';
                                vm.devMaintenRepair.faultId = '';
                                vm.devMaintenRepair.faultCode = '';
                                vm.devMaintenRepair.faultDesc = '';
                            });
                        });
                        layer.close(index);
                    }
                }
            })
        },
        query: function () {
            vm.reload();
        },
        getFaultTree: function () {
            //加载故障类型树
            Ajax.request({
                url: "../alarmcategory/queryAll",
                async: true,
                successCallback: function (r) {
                    var tree = r.list;
                    faultTree = $.fn.zTree.init($("#faultTree"), setting, tree);
                    //faultTree.expandNode(faultTree.getNodeByParam("id", '0', null));
                }
            });
        },
        getFaultTypeTree: function () {
            //加载故障类型树
            Ajax.request({
                url: "../alarmcategory/queryAll",
                async: true,
                successCallback: function (r) {
                    var tree = r.list;
                    formAlarmCategoryTree = $.fn.zTree.init($("#faultTypeTree"), alarmCategoryTreeSetting, tree);
                    // formAlarmCategoryTree.expandNode(faultTree2.getNodeByParam("id", '70', null));
                }
            });
        },
        add: function () {
            vm.showList = false;
            /*
            * 1.清空vfg 和 ccc数组*/
            vm.vfgList = [];
            vm.cccList = [];
            vm.flag = 0;
            vm.title = "请按照从上到下的顺序，补录设备维修记录";
            vm.devMaintenRepair = {
                devId: '',
                devCode: '',
                devName: '',
                maintenRecordId: '',
                faultCode: '',
                faultDesc: '',
                faultId: '',
                vrtId: '',
                vfgId: '',
                faultCategoryId: '', // 报警分类名称
                faultCategoryName: '', // 报警分类名称
                recordDescr: '',
                reason: '',
                solution: '',
                remark: '',
                id: '',
                startDateTime: '', // Date-Picker组件用
                endDateTime: '', // Date-Picker组件用
                repairStartDate: '',
                repairEndDate: ''
            };
            //查询设备列表
            Ajax.request({
                url: "../deviceinfo/deviceInfoAll",
                async: true,
                successCallback: function (r) {
                    vm.deviceInfoList = r.list;
                }
            })
            vm.getFaultTypeTree();
        },
        update: function (event) {
            var id = getSelectedRow("#jqGrid");
            if (id == null) {
                return;
            }
            vm.showList = false;
            vm.title = "修改";
            Ajax.request({
                url: "../deviceinfo/deviceInfoAll",
                async: false,
                successCallback: function (r) {
                    vm.deviceInfoList = r.list;
                }
            });
            vm.getFaultTypeTree();
            vm.getInfo(id);
        },
        saveOrUpdate: function (event) {
            if (vm.devMaintenRepair.startDateTime) {
                vm.devMaintenRepair.repairStartDate = gmt2DateTimeStr(vm.devMaintenRepair.startDateTime)
            }
            if (vm.devMaintenRepair.endDateTime) {
                vm.devMaintenRepair.repairEndDate = gmt2DateTimeStr(vm.devMaintenRepair.endDateTime)
            }
            var url = vm.devMaintenRepair.id == (null || '') ? "../devmaintenrepair/addRepairRecord" : "../devmaintenrepair/update";
            let starDate = new Date(vm.devMaintenRepair.repairStartDate).getTime();
            let endTime = new Date(vm.devMaintenRepair.endDateTime).getTime();
            let eight = 8 * 60 * 60 * 1000;
            if ((endTime - starDate) > eight) {
                confirm('当前维修时长已超过8小时，是否确认输入正确的维修开始和维修结束时间？', function () {
                    Ajax.request({
                        url: url,
                        params: JSON.stringify(vm.devMaintenRepair),
                        type: "POST",
                        contentType: "application/json",
                        successCallback: function (r) {
                            alert('操作成功', function (index) {
                                vm.reload();
                            });
                        }
                    });
                })
            } else {
                Ajax.request({
                    url: url,
                    params: JSON.stringify(vm.devMaintenRepair),
                    type: "POST",
                    contentType: "application/json",
                    successCallback: function (r) {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            }
        },
        del: function (event) {
            var ids = getSelectedRows("#jqGrid");
            if (ids == null) {
                return;
            }
            confirm('确定要删除选中的记录？', function () {
                Ajax.request({
                    url: "../devmaintenrepair/delete",
                    params: JSON.stringify(ids),
                    type: "POST",
                    contentType: "application/json",
                    successCallback: function () {
                        alert('操作成功', function (index) {
                            layer.closeAll();
                            vm.reload();
                        });
                    }
                });
            });
        },
        // 添加维修记录
        viewRepairDetail: function (ticketId) {
            openWindow({
                type: 2,
                area:['100%','100%'],
                title: '<i class="fa fa-bars"></i> 完善维修记录',
                content: '../device/perfectRepairRecord.html?id=' + ticketId,//+'&workId'+date.id
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var iframeWin = window["layui-layer-iframe" + index];
                    var devRepairRecord = iframeWin.getDateform();
                    if (devRepairRecord.repairStartDate) {
                        devRepairRecord.repairStartDate = gmt2DateTimeStr(devRepairRecord.repairStartDate);
                    }
                    if (devRepairRecord.repairEndDate) {
                        devRepairRecord.repairEndDate = gmt2DateTimeStr(devRepairRecord.repairEndDate);
                    }
                    if (!devRepairRecord.faultCategoryId) {
                        alert('设备报警CCC必选！');
                        return;
                    }
                    // 获取请求URL
                    Ajax.request({
                        url: "../devmaintenrepair/save",
                        params: JSON.stringify(devRepairRecord),
                        type: "POST",
                        contentType: "application/json",
                        successCallback: function (r) {
                            alert('操作成功', function () {
                                layer.close(index);
                                vm.reload();
                            });
                        }
                    });

                }
            });
        },
        getInfo: function (id) {
            Ajax.request({
                url: "../devmaintenrepair/info/" + id,
                async: true,
                successCallback: function (r) {
                    vm.showList = false;
                    vm.title = "维修记录详情";
                    vm.devMaintenRepair = r.devMaintenRepair;
                }
            });
        },
        reload: function (event) {
            vm.showList = true;
            if (this.q.beginTime) {
                this.q.beginTime = gmt2DateStr(this.q.beginTime);
            }
            if (this.q.endTime) {
                this.q.endTime = gmt2DateStr(this.q.endTime);
            }
            // $("#jqGrid").setGridWidth($(window).width());
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: this.q,
                page: page
            }).trigger("reloadGrid");
            vm.handleReset('formValidate');
        },
        reloadSearch: function () {
            this.q = {
                workshopId: '',
                devCode: '',
                name: '', // 设备名称
                spareName: '', // 备件名称
                spareSpec: '', // 备件规格
                faultCategoryId: '', // 报警/故障分类ID
                beginTime: '',
                endTime: '',
            };
            this.repairStartRange = [];
            this.reload();
            faultTree.cancelSelectedNode();
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        },
        getByDevCode: function (id) {
            if (!id) {
                return;
            }
            Ajax.request({
                url: "../deviceinfo/info/" + id,
                type: 'POST',
                successCallback: function (r) {
                    var deviceInfo = r.deviceInfo;
                    vm.devMaintenRepair.devId = deviceInfo.id;
                    vm.devMaintenRepair.devCode = deviceInfo.devCode;
                    vm.devMaintenRepair.devName = deviceInfo.devName;
                }
            });
        },
        handleRepairStartRangeChange(dateVal, dateType) {
            this.q.beginTime = dateVal[0];
            this.q.endTime = dateVal[1];
        }
    }
});
